package com.sskj.gcc.ui.fragment;


import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.NumberUtil;

import com.sskj.depthlib.data.DepthData;
import com.sskj.depthlib.view.DepthMapView;
import com.sskj.gcc.R;
import com.sskj.gcc.bean.rxbus.MarketCoinBean;
import com.sskj.gcc.presenter.DeepthFragmentPresenter;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.WSFiveBean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.APP_FRAGMENT_DEEPTH)
public class DeepthFragment extends BaseFragment<DeepthFragmentPresenter> {
    @Autowired
    String code;
    @BindView(R.id.tvBuyNumTitle)
    TextView tvBuyNumTitle;
    @BindView(R.id.tvSellNumTitle)
    TextView tvSellNumTitle;
    @BindView(R.id.recyclerViewBuy)
    RecyclerView buyRecyclerView;
    @BindView(R.id.recyclerViewSell)
    RecyclerView sellRecyclerView;
    @BindView(R.id.depthMapView)
    DepthMapView depthMapView;
    private SlimAdapter sellSlimAdapter;
    private SlimAdapter buySlimAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_deepth;
    }

    @Override
    public void onResume() {
        getView().setFocusable(true);
        getView().setFocusableInTouchMode(true);
        super.onResume();
    }

    @Override
    public DeepthFragmentPresenter getPresenter() {
        return new DeepthFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        String replace = code.replace("_", "/");
        tvBuyNumTitle.setText(String.format(App.INSTANCE.getString(R.string.appJavaDeepthFragment3), replace.substring(0, replace.indexOf("/"))));
        tvSellNumTitle.setText(String.format(App.INSTANCE.getString(R.string.appJavaDeepthFragment3), replace.substring(0, replace.indexOf("/"))));

        initRecy();
    }

    @Override
    public void initData() {
        mPresenter.getData(code);
        mPresenter.initSocket(code);
    }

    private void initRecy() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        sellSlimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_deep_sell, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().indexOf(data) + 1 + "")
//                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : NumberUtil.keepMax(data.getPrice(), code.toUpperCase().contains("USDT") ? 4 : 8))
                        .text(R.id.tvNum, data.getTotalSize());
            }
        }).attachTo(sellRecyclerView).updateData(new ArrayList());
        buySlimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_deep_buy, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : NumberUtil.keepMax(data.getPrice(), code.toUpperCase().contains("USDT") ? 4 : 8))
//                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, BuySellEnum.BUY.getColorRes()))
                        .text(R.id.tvNum, data.getTotalSize());
            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
        sellRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    buyRecyclerView.scrollBy(dx, dy);
                }
            }
        });
        buyRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    sellRecyclerView.scrollBy(dx, dy);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeCoin(MarketCoinBean marketCoinBean) {
        code = marketCoinBean.getCode();
        if (tvSellNumTitle == null) {
            return;
        }
        String replace = code.replace("_", "/");
        tvBuyNumTitle.setText(String.format(App.INSTANCE.getString(R.string.appJavaDeepthFragment3), replace.substring(0, replace.indexOf("/"))));
        tvSellNumTitle.setText(String.format(App.INSTANCE.getString(R.string.appJavaDeepthFragment3), replace.substring(0, replace.indexOf("/"))));
        mPresenter.getData(code);
        mPresenter.sendCode(code);
    }

    public void updateUIDown(WSFiveBean data) {
        if (data == null || buySlimAdapter == null) {
            return;
        }
        ArrayList<WSFiveBean.FiveBean> buyFiveBean = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> sellFiveBean = new ArrayList<>();
        Flowable.fromIterable(data.getAsks())
                .take(15)
                .map(fiveBean -> buyFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice())))
                .subscribe();
        Flowable.fromIterable(data.getBids())
                .take(15)
                .map(fiveBean -> sellFiveBean.add(new WSFiveBean.FiveBean(fiveBean.getDoubleTotalSize(), fiveBean.getPrice())))
                .subscribe();

        buySlimAdapter.updateData(sellFiveBean);
        sellSlimAdapter.updateData(buyFiveBean);
    }

    public void updateUI(WSFiveBean data) {
        Collections.reverse(data.getBids());
        Flowable<List<DepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                .map(fiveBean -> new DepthData(Float.valueOf(fiveBean.getDoubleTotalSize()), Float.valueOf(fiveBean.getPrice())))
                .toList()
                .toFlowable();
        Flowable<List<DepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                .map(fiveBean -> new DepthData(Float.valueOf(fiveBean.getDoubleTotalSize()), Float.valueOf(fiveBean.getPrice())))
                .toList()
                .toFlowable();

        Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {
            if (depthMapView == null) {
                return "0";
            }
            depthMapView.setData(buyData, sellData);
            return "1";
        }).subscribe();
    }


    @Override
    public void onDestroy() {
        mPresenter.closeWebSocket();
        super.onDestroy();
    }
}
